package org.marsson.bNav;

public class Packet {
	char inicial;
	private int x;
	private int y;
	private char acertou;
	private  byte check;
	String packet;
	
	public Packet(String string)throws InvalidPacketException{
		if (string.length()!=5){
			throw new InvalidPacketException();
		}
		packet = string;
		inicial = string.charAt(0);
		x =Integer.parseInt( string.substring(1, 2), 16 /* radix */ );
		y = Integer.parseInt( string.substring(2, 3), 16 /* radix */ );
		acertou = string.charAt(3);
		check = (byte)string.charAt(4);	
		checkCheck();	
	}
	
	public Packet(int x, int y, char acertou) throws InvalidPacketException{
		this.inicial='T';
		this.x=x;
		this.y=y;
		this.acertou=acertou;
		System.out.println(Integer.toHexString(15));
		packet =inicial+Integer.toHexString(x)+Integer.toHexString(y)+acertou+createCheck();
	}
	public char createCheck() throws InvalidPacketException{
		check = (byte)((x+y+(byte)inicial)+(byte)acertou);
		if (check<0)
		{
			check = (byte) (check*-1);
		}
		checkCheck();
		return (char) check;
		
	}
	public String getPacket() {
		return packet;
	}
	public void setPacket(String packet) {
		this.packet = packet;
	}
	public void checkCheck() throws InvalidPacketException{
		if(check==(byte)((x+y+(byte)inicial)+(byte)acertou)|| check==(byte)(((x+y+(byte)inicial)+(byte)acertou)*-1))
		{
			System.out.println("OK");
			
		}
		else{
			System.out.println("Verificacao 1 vale: "+(byte)((x+y+(byte)inicial)+(byte)acertou));
			System.out.println("Verificacao 2 vale: "+(byte)(((x+y+(byte)inicial)+(byte)acertou)*-1));
			System.out.println("Check vale "+check);
			throw new InvalidPacketException();
		}
		
	}
	
	public char getInicial() {
		return inicial;
	}

	public void setInicial(char inicial) {
		this.inicial = inicial;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public char getAcertou() {
		return acertou;
	}

	public void setAcertou(char acertou) {
		this.acertou = acertou;
	}

	public byte getCheck() {
		return check;
	}

	public void setCheck(byte check) {
		this.check = check;
	}
	public static void main(String args[]) {
       try {
		Packet packet = new Packet("Tf2NM");
		Packet packet2 = new Packet(15,2,'N');
		System.out.println(packet2.getPacket());
	} catch (InvalidPacketException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
	
}
